package org.dromara.business.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.constants.RepeaterConstant;
import org.dromara.business.domain.Events;
import org.dromara.business.domain.vo.RepeaterMessageVo;
import org.dromara.business.mongoMapper.EventsMongoRepository;
import org.dromara.business.service.EventsService;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class EventsServiceImpl implements EventsService {

    private final EventsMongoRepository eventsRepository;

    @Override
    public TableDataInfo<Events> pageEvents(Events events, PageQuery pageQuery) {
        // 1. 创建匹配器（可设置模糊查询规则，如模糊查询）
        ExampleMatcher matcher = ExampleMatcher.matching()
            // 对 name 字段进行模糊查询（默认是精确匹配）
            // 忽略空值字段（不将 null 作为查询条件）
            .withIgnoreNullValues();
        // 创建排序条件
        Sort sort = Sort.by(Sort.Direction.DESC, "createdAt");

        // 创建分页请求，包含排序
        Pageable pageable = PageRequest.of(pageQuery.getPageNum()-1, pageQuery.getPageSize(), sort);
        // 2. 构建 Example（查询查询条件 + 匹配规则）
        Example<Events> example = Example.of(events, matcher);

        // 4. 执行查询
        Page<Events> eventsPage = eventsRepository.findAll(example, pageable);
        return TableDataInfo.build(eventsPage);
    }

    @PostConstruct
    public void init() {
        RedisUtils.subscribe(RepeaterConstant.REPEATER_SENDED, RepeaterMessageVo.class, messageVo->{
//            log.info(messageVo);
//            JSONObject obj = JSONUtil.parseObj(msgStr);
//            Boolean status = obj.getBool("status");
//            SseMessageDto dto = new SseMessageDto();
//            if(status){
//                dto.setMessage(StrUtil.format("交易【{}】发送成功", obj.getStr("id")));
//            }else{
//                dto.setMessage(StrUtil.format("交易【{}】发送失败", obj.getStr("id")));
//            }
//            dto.setUserIds(List.of(obj.getLong("userId")));
//            SseMessageUtils.publishMessage(dto);

            SseMessageDto dto = new SseMessageDto();
            if(messageVo.getStatus()){
                dto.setMessage(StrUtil.format("交易【{}】发送成功", messageVo.getId()));
            }else{
                dto.setMessage(StrUtil.format("交易【{}】发送失败", messageVo.getId()));
            }
            dto.setUserIds(List.of(messageVo.getUserId()));
            SseMessageUtils.publishMessage(dto);
        });
    }
}
